package com.itheima.filter;


import com.itheima.bean.Employee;
import com.itheima.bean.User;
import com.itheima.util.BaseContext;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebFilter("/*")
public class FrontFilter implements  Filter{
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)servletRequest;
        HttpServletResponse resp=(HttpServletResponse)servletResponse;
        //获取当前的请求地址
//        System.out.println("front");
        String uri=req.getRequestURI();
//        System.out.println("来到过滤器了uri = " + uri);

        /*
        判断请求地址是不是直接放行地址
         */
        if (uri.contains("login")||uri.contains("images")||uri.contains("backend")
             ||uri.endsWith(".js")||uri.endsWith(".ico")||uri.contains("fonts")||uri.contains("sms")||uri.contains("sendCode")){
//            System.out.println("front dofilter");
            filterChain.doFilter(servletRequest,servletResponse);
            return ;
        }
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");

        Employee employee=(Employee)session.getAttribute("employee");
        if (employee!=null){
            filterChain.doFilter(servletRequest,servletResponse);
            return ;
        }
        if (user!=null){
            BaseContext.setCurrentId(user.getId());
            filterChain.doFilter(servletRequest,servletResponse);
            return ;
        }
        resp.sendRedirect("/front/page/login.html");
    }
}
